import { Inject, Injectable } from '@nestjs/common';
import * as container from 'rhea'
import { randomUUID, createHmac } from 'crypto'
import { ConnectOptions } from './type/ConnectOptions';



@Injectable()
export class AmqpClientService {
    private connection:container.Connection;
    constructor(
		@Inject('AMQP_CONNECT_OPTIONS') private options: ConnectOptions,
	) {
		const timestamp = Math.floor(Date.now() / 1000)
        let username = `${randomUUID()}|authMode=aksign,signMethod=hmacsha1,timestamp=${timestamp},authId=${options.accessKeyId}`
        if(options.instanceId) {
        username += (`,iotInstanceId=${options.instanceId}`)
        }

        username += (`,consumerGroupId=${options.consumerGroupId}|`)

        const password = Buffer.from(createHmac('sha1', options.accessKeySecret).update('authId='+ options.accessKeyId +'&timestamp=' + timestamp).digest()).toString('base64')

        this.connection = container.connect({
            //接入域名，请参见AMQP客户端接入说明文档。
            'host': `${options.uid}.iot-amqp.${options.regionId}.aliyuncs.com`,
            'port': 5671,
            'transport':'tls',
            'reconnect':true,
            'idle_time_out':60000,
            //userName组装方法，请参见AMQP客户端接入说明文档。
            'username': username, 
            //计算签名，password组装方法，请参见AMQP客户端接入说明文档。
            'password': password,
        })


        this.connection.open_receiver()
	}

    on(event:string, callback:(...args:any[]) => void) {
        this.connection.on(event, callback)
    }
}
